﻿using System.Collections.Generic;
using System.Linq;

using Microsoft.SqlServer.Management.SqlParser.SqlCodeDom;

namespace iTool.SQL.AIHandle.OrderByClause
{
    public class SqlOrderByItemAnalysis : SqlAnalysisBase
    {
        public SqlOrderByItemAnalysis(SqlAnalysisContext context) : base(context)
        {
        }

        public override void Analysis()
        {
            var sqlOrderByItem = (SqlOrderByItem)base.CodeObject;
            base.Context.SortByOptions ??= new List<SortByOptions>();
            var first = base.Context.SortByOptions.Where(item => item.SubIndex == this.Context.SubIndex).FirstOrDefault();
            if (first != null)
            {
                base.Context.SortByOptions.Remove(first);
                base.Context.SortByOptions.Add(first);
            }
            else
            {
                base.Context.SortByOptions.Add(new SortByOptions
                {
                    SubIndex = this.Context.SubIndex,
                    SortOrder = sqlOrderByItem.SortOrder,
                    OrderCase = base.CodeObject.Parent.Sql
                });
            }

            base.Next();

        }

        public override bool Validation(SqlCodeObject codeObject) => true;
    }
}
